// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

// 云函数入口函数
exports.main = async (event, context) => {
  // 源数据深拷贝保存
  const _data = JSON.parse(JSON.stringify(event))
  // 结果保存
  const result = {}
  // 处理 users 数据库中的内容
  const user = cloud.database().collection('users')
  const { data } = await user.where({
    _id: parseInt(_data._id)
  }).get()
  const commentId = data[0].comments[_data.index].commentId
  delete data[0]._id
  data[0].comments.splice(_data.index, 1)
  result.result1 = await user.where({
    _id: parseInt(_data._id)
  }).update({
    data: data[0]
  })
  // 处理 comments 数据库中的内容
  const commentsDb = cloud.database().collection('comments')
  const commentData = await commentsDb.where({
    commentId
  }).get()
  const comment = commentData.data[0]
  // return comment
  // 处理 books 数据库中的内容
  const booksDb = cloud.database().collection('books')
  const bookData = await booksDb.where({
    bookId: comment.bookId
  }).get()
  const book = bookData.data[0]
  delete book._id
  const newcComments = book.comments.filter(item => item.commentId !== comment.commentId)
  book.comments = newcComments
  booksDb.where({
    bookId: comment.bookId
  }).update({
    data: book
  })
  result.result2 = await commentsDb.where({
    commentId
  }).remove()
  return {
    result
  }
}
